from typing import Dict, Any
import time
from agents.workflow import create_wealth_advisor_workflow

# 示例客户画像数据（从原始 monolith 提取）
SAMPLE_CUSTOMER_PROFILES = {
    "customer1": {
        "customer_id": "C10012345",
        "risk_tolerance": "平衡型",
        "investment_horizon": "中期",
        "financial_goals": ["退休规划", "子女教育金"],
        "investment_preferences": ["ESG投资", "科技行业"],
        "portfolio_value": 1500000.0,
        "current_allocations": {"股票": 0.40, "债券": 0.30, "现金": 0.10, "另类投资": 0.20},
    },
    "customer2": {
        "customer_id": "C10067890",
        "risk_tolerance": "进取型",
        "investment_horizon": "长期",
        "financial_goals": ["财富增长", "资产配置多元化"],
        "investment_preferences": ["新兴市场", "高成长行业"],
        "portfolio_value": 3000000.0,
        "current_allocations": {"股票": 0.65, "债券": 0.15, "现金": 0.05, "另类投资": 0.15},
    },
}

# 运行智能体
def run_wealth_advisor(user_query: str, customer_id: str = "customer1") -> Dict[str, Any]:
    """运行财富顾问智能体并返回结果"""
    
    # 创建工作流
    agent = create_wealth_advisor_workflow()
    
    # 获取客户画像
    customer_profile = SAMPLE_CUSTOMER_PROFILES.get(customer_id, SAMPLE_CUSTOMER_PROFILES["customer1"])
    
    # 准备初始状态
    initial_state = {
        "user_query": user_query,
        "customer_profile": customer_profile,
        "query_type": None,
        "processing_mode": None,
        "emergency_response": None,
        "market_data": None,
        "analysis_results": None,
        "final_response": None,
        "current_phase": "assess",
        "error": None
    }
    
    try:
        print("LangGraph Mermaid流程图：")
        print(agent.get_graph().draw_mermaid())

        # 运行智能体并捕获可能的异常
        print(f"[runner] 开始执行工作流 时间={time.strftime('%Y-%m-%d %H:%M:%S')}")
        start = time.time()
        result = agent.invoke(initial_state)
        elapsed = time.time() - start
        print(f"[runner] 工作流执行结束 用时 {elapsed:.2f}s 时间={time.strftime('%Y-%m-%d %H:%M:%S')}")
        return result
    except Exception as e:
        error_msg = str(e)
        print(f"捕获异常: {error_msg}")
        # 返回带有错误信息的状态
        return {
            **initial_state,
            "error": f"执行过程中发生错误: {error_msg}",
            "final_response": "很抱歉，处理您的请求时出现了问题。"
        }


